﻿// 链表节点
using System;

public class Node<T>
{
    public Node<T> Next { get; set; }
    public T Data { get; set; }

    public Node(T t)
    {
        Next = null;
        Data = t;
    }
}

//泛型链表类
public class GenericList<T> where T : IComparable<T>
{
    private Node<T> head;
    private Node<T> tail;

    public GenericList()
    {
        tail = head = null;
    }

    public Node<T> Head
    {
        get => head;
    }

    public void Add(T t)
    {
        Node<T> n = new Node<T>(t);
        if (tail == null)
        {
            head = tail = n;
        }
        else
        {
            tail.Next = n;
            tail = n;
        }
    }

    // 添加 ForEach 方法
    public void ForEach(Action<T> action)
    {
        Node<T> current = head;
        while (current != null)
        {
            action(current.Data);
            current = current.Next;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        // 整型List
        GenericList<int> intList = new GenericList<int>();
        for (int x = 0; x < 10; x++)
        {
            intList.Add(x);
        }

        // 打印链表元素
        Console.WriteLine("链表元素:");
        intList.ForEach(item => Console.Write(item + " "));
        Console.WriteLine();

        // 求最大值
        int max = int.MinValue;
        intList.ForEach(item => {
            if (item.CompareTo(max) > 0)
            {
                max = item;
            }
        });
        Console.WriteLine("最大值: " + max);

        // 求最小值
        int min = int.MaxValue;
        intList.ForEach(item => {
            if (item.CompareTo(min) < 0)
            {
                min = item;
            }
        });
        Console.WriteLine("最小值: " + min);

        // 求和
        int sum = 0;
        intList.ForEach(item => sum += item);
        Console.WriteLine("求和: " + sum);


        // 字符串型List
        GenericList<string> strList = new GenericList<string>();
        for (int x = 0; x < 10; x++)
        {
            strList.Add("str" + x);
        }

        // 打印链表元素
        Console.WriteLine("\n链表元素:");
        strList.ForEach(item => Console.Write(item + " "));
        Console.WriteLine();
    }
}